package com.jcx.ldzj.utile;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.*;
@Slf4j
public class FileUtile {

	/**
	 * 储存文件地址
	 */
	private static List<String> fileNamePaths=new ArrayList();
	/**
	 * 储存文件
	 */
	private static List<File> filepaths=new ArrayList();
	/**
	 * 储存文件和地址
	 */
	private static Map<String,File> fileMap=new HashMap<>();

	public static void main(String[] args) {
		System.out.println("11");
	}
	/**
	 * 读取对应地址文件
	 * @param file
	 * @return
	 */
	private static String read(String file) {
		// 创建字节流对象，并根据已创建的字节流对象创建字节流对象
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader raf = null;
		String x="";
		String s = "";
		try {
			
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis);
			raf = new BufferedReader(isr);
			while((s = raf.readLine()) != null) {
				System.out.println(s);
				x = x+s;
			
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return x;
	}

	/**
	 * io流读取base64位字节码解析生成文件
	 * @param base64
	 * @param fileName
	 * @param savePath
	 */
	public static void base64ToFile(String base64, String fileName, String savePath) {
		File file = null;
		// 创建文件目录
		String filePath = savePath;
		File dir = new File(filePath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
		BufferedOutputStream bos = null;
		java.io.FileOutputStream fos = null;
		try {
			byte[] bytes = Base64.getDecoder().decode(base64);
			file = new File(filePath + fileName);
			fos = new java.io.FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}



	/**
	 * 获取对应目录下的所有文件
	 * @param filepath
	 * @return
	 */
	public static List<File> getFilepaths(String filepath){
		filepaths=new ArrayList();
		if(FileUtile.readfile(filepath)){
			return filepaths;
		}
		return filepaths;
	}

	/**
	 * 获取对应目录下的文件的map集合
	 * @param filepath
	 * @return
	 */
	public static Map<String,File> getFileMap(String filepath){
		fileMap=new HashMap<>();
		if(FileUtile.readfile(filepath)){
			return fileMap;
		}
		return fileMap;
	}

	/**
	 * 获取对应文件目录下的所有文件地址
	 * @param filepath
	 * @return
	 */
	public static List<String> getFileNamePaths(String filepath){
		fileNamePaths=new ArrayList();
		if(FileUtile.readfile(filepath)){
			return fileNamePaths;
		}
		return fileNamePaths;
	}
	/**
	 * 读取某个文件夹下的所有文件
	 * @param filepath 文件夹地址
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static boolean readfile(String filepath) {
		try {
			File file = new File(filepath);
			if (!file.isDirectory()) {
				fileNamePaths.add(file.getPath());
				filepaths.add(file);
				fileMap.put(file.getPath(),file);
				log.info("文件!!!!!!!!!!!");
				log.info("path={}" , file.getPath());
				log.info("absolutepath={}" , file.getAbsolutePath());
				log.info("name={}" , file.getName());

			} else if (file.isDirectory()) {
				System.out.println("文件夹");
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "\\" + filelist[i]);
					log.info("文件夹!!!!!!!!!!!");
					if (!readfile.isDirectory()) {
						log.info("path={}" , readfile.getPath());
						log.info("absolutepath={}",readfile.getAbsolutePath());
						log.info("name={}" , readfile.getName());

					} else if (readfile.isDirectory()) {
						readfile(filepath + "\\" + filelist[i]);
					}
				}

			}

		} catch (Exception e) {
			log.error("读取某个文件夹下的所有文件时出错，错误原因：{}" , e.getMessage());
		}
		return true;
	}

	/**
	 * 说明：根据指定URL获取文件内容
	 *
	 * @param urlPath
	 *            下载路径
	 *  return 文件内容
	 */
	public static String downloadFile(String urlPath) {
		StringBuffer buffer=new StringBuffer();
		try {
			// 统一资源
			URL url = new URL(urlPath);
			// 连接类的父类，抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			//设置超时
			httpURLConnection.setConnectTimeout(1000*5);
			//设置请求方式，默认是GET
			httpURLConnection.setRequestMethod("POST");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
			httpURLConnection.connect();
			// 建立链接从请求中获取数据
			BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
			int size = 0;
			byte[] buf = new byte[2048];
			while ((size = bin.read(buf)) != -1) {
				String str = new String(buf, "UTF-8");
				buffer.append(str);
			}
			// 关闭资源
			bin.close();
			log.info("文件下载成功！文件本身大小约为{}KB",httpURLConnection.getContentLength()/ 1024);
		} catch (MalformedURLException e) {
			log.info("文件下载失败！错误原因：{}",e);
			buffer.append("文件下载失败！错误原因：{}"+e);
		} catch (IOException e) {
			log.info("文件下载失败！错误原因：{}",e);
			buffer.append("文件下载失败！错误原因：{}"+e);
		} finally {
			return buffer.toString();
		}

	}

	/**
	 * 这个包不能pom导入，除非自身本地有对应的包
	 * 必须要自己下载的包，jave-1.0.2
	 * @param source
	 * @return
	 */
	private String ReadVideoTime(File source) {
		Encoder encoder = new Encoder();
		String length = "";
		try {
			MultimediaInfo m = encoder.getInfo(source);
			long ls = m.getDuration()/1000;
			int hour = (int) (ls/3600);
			int minute = (int) (ls%3600)/60;
			int second = (int) (ls-hour*3600-minute*60);
			length = hour+"'"+minute+"''"+second+"'''";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return length;
	}
	/**
	 * 获取视频大小
	 * @param source
	 * @return
	 */
	private String ReadVideoSize(File source) {
		FileChannel fc= null;
		String size = "";
		try {
			@SuppressWarnings("resource")
			FileInputStream fis = new FileInputStream(source);
			fc= fis.getChannel();
			BigDecimal fileSize = new BigDecimal(fc.size());
			size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null!=fc){
				try{
					fc.close();
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
		return size;
	}
}